package com.mingtu.jgspatrol.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.CustomDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.contacts.activity.ContactsActivity;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.ChargeAreaActivity;
import com.mingtu.jgspatrol.activity.ExchangeActivity;
import com.mingtu.jgspatrol.activity.MyRecordActivity;
import com.mingtu.jgspatrol.activity.NotificationActivity;
import com.mingtu.jgspatrol.activity.RecordActivity;
import com.mingtu.jgspatrol.activity.ReportTypeActivity;
import com.mingtu.jgspatrol.activity.ResultStatisticsActivity;
import com.mingtu.jgspatrol.activity.TaskListActivity2;
import com.mingtu.jgspatrol.adapter.MenuAdapter2;
import com.mingtu.jgspatrol.adapter.NoticeBannerAdapter;
import com.mingtu.jgspatrol.bean.IndexNewsBean;
import com.mingtu.jgspatrol.bean.NoticeBean;
import com.mingtu.jgspatrol.callback.MyStringDialogCallback;
import com.mingtu.jgspatrol.databinding.FragmentIndex2Binding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class IndexFragment2 extends BaseBindingFragment<FragmentIndex2Binding> implements LazyFragmentPagerAdapter.Laziable {
    private SmartRefreshLayout srlUp;
    private List<String> list = new ArrayList<>();
    private List<IndexNewsBean.DataBean> DataBean = new ArrayList<>();
    private NoticeBannerAdapter noticeBannerAdapter;
    private boolean isLeader = SPStaticUtils.getBoolean(SPTools.isLeader);
    public static IndexFragment2 getInstance() {
        IndexFragment2 fragment = new IndexFragment2();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_index2;
    }

    @Override
    protected void initData() {
        addClickListener(this, binding.layoutMoreNews,  binding.layoutReport, binding.layoutBook, binding.layoutTask, binding.layoutMsgNotice, binding.layoutUnitNotice);

    }

    @Override
    protected void initView() {

        //其它
        MenuAdapter2 menuAdapter = new MenuAdapter2(getContext(),isLeader);
        binding.gridView.setAdapter(menuAdapter);
        menuAdapter.setOnItemClickListener(new MenuOnItenClickListner());


        LinearLayoutManager manager = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager);

        //添加自定义分割线
        binding.recycler.addItemDecoration(new CustomDecoration(getActivity(), CustomDecoration.VERTICAL_LIST, R.drawable.shape_dive_line, 0));

        initListener();

    }

    @Override
    protected void getData() {
        getNewList(5);
        getMessageCount();
        getUndoTaskCount();
        getUnitNotice();
    }

    private void initListener() {
        initPullRefresh();//刷新
    }


    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setEnableLoadMore(false);
        srlUp.setEnableOverScrollDrag(true);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                getNewList(5);
                getMessageCount();
                getUndoTaskCount();
                getUnitNotice();
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.layout_more_news:
                //新闻政策
                Bundle bundle = new Bundle();
                bundle.putInt("type", 5);
                IntentUtils.getInstance().readyGo(getActivity(), ExchangeActivity.class, bundle);
                break;
            case R.id.layout_report:
                //上报
                IntentUtils.getInstance().readyGo(getActivity(), ReportTypeActivity.class);
                break;
            case R.id.layout_book:
                IntentUtils.getInstance().readyGo(getActivity(), ContactsActivity.class);
                break;
            case R.id.layout_task:
                //待办任务
                IntentUtils.getInstance().readyGo(getActivity(), TaskListActivity2.class);
                break;
            case R.id.layout_msg_notice:
                //消息通知
                Bundle bundle1 = new Bundle();
                bundle1.putInt("type", 1);
                IntentUtils.getInstance().readyGo(getActivity(), NotificationActivity.class, bundle1);
                break;
            case R.id.layout_unit_notice:
                //单位通知
                Bundle bundle2 = new Bundle();
                bundle2.putInt("type", 0);
                IntentUtils.getInstance().readyGo(getActivity(), NotificationActivity.class, bundle2);
                break;
        }
    }
    
    private class MenuOnItenClickListner implements MenuAdapter2.OnItemClickListener {

        @Override
        public void onItemClick(View view, int position) {
            switch (position) {
                case 0:
                    //责任区
                    IntentUtils.getInstance().readyGo(getActivity(), ChargeAreaActivity.class);
                    break;
                case 1:
                    //任务单
                    IntentUtils.getInstance().readyGo(getActivity(), TaskListActivity2.class);
                    break;
                case 2:
                    //记录单
                    boolean recordAuth = SPStaticUtils.getBoolean(SPTools.recordAuth);
                    if (recordAuth) {
                        IntentUtils.getInstance().readyGo(getActivity(), RecordActivity.class);
                    } else {
                        IntentUtils.getInstance().readyGo(getActivity(), MyRecordActivity.class);
                    }

                    break;
                case 3:
                    //成果单
                    IntentUtils.getInstance().readyGo(getActivity(), ResultStatisticsActivity.class);
                    break;
                case 6:
                    //学习新闻
                    Bundle bundle2 = new Bundle();
                    bundle2.putInt("type", 2);
                    IntentUtils.getInstance().readyGo(getActivity(), ExchangeActivity.class, bundle2);
                    break;
            }

        }
    }

    private void getNewList(int num) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("num", num);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INDEX_NEWS_LIST + "/" + num)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                IndexNewsBean indexNewsBean = new IndexNewsBean();
                                indexNewsBean = gson.fromJson(result, IndexNewsBean.class);
                                List<IndexNewsBean.DataBean> dataBeans = indexNewsBean.getData();
                                try {
                                    binding.emptyLayout.setIsShowView(false);
                                    binding.recycler.setVisibility(View.VISIBLE);
                                    if (dataBeans != null && dataBeans.size() > 0) {
                                        DataBean.addAll(dataBeans);
//                                        indexJobAdapter.upData(DataBean);
                                    } else {
                                        binding.recycler.setVisibility(View.GONE);
                                        binding.emptyLayout.setIsShowView(true);
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    binding.recycler.setVisibility(View.GONE);
                                    binding.emptyLayout.setIsShowView(true);
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                binding.emptyLayout.setIsShowView(true);
                                binding.recycler.setVisibility(View.GONE);
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
                            }

                        }
                    }
                });
    }

    /**
     * 获取未读消息的个数
     */
    public void getMessageCount() {
        OkGo.<String>post(MyConstant.POST_MESSAGE_COUNT)
                .tag(this)
                .upJson("")
                .execute(new MyStringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                String data = jsonObject.getString("data");
                                if (!StringUtils.isEmpty(data)) {
                                    try {
                                        binding.tvMessageNum.setText(data + "");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 获取未完成任务数
     */
    public void getUndoTaskCount() {
        OkGo.<String>post(MyConstant.POST_UNDOTASK_COUNT)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                String data = jsonObject.getString("data");
                                if (!StringUtils.isEmpty(data)) {
                                    binding.tvTaskNum.setText(data + "");
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 单位通知
     */
    private void getUnitNotice() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", 1);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("contentType", 4);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_NEWS_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                NoticeBean messageBean = new NoticeBean();
                                messageBean = gson.fromJson(result, NoticeBean.class);
                                List<NoticeBean.PageBean.ListBean> dataBeans = messageBean.getPage().getList();

                                if (dataBeans != null) {
                                    int size = dataBeans.size();
                                    if (size > 0) {
                                        List<NoticeBean.PageBean.ListBean> myDataBeans = new ArrayList<>();
                                        if (size > 3) {
                                            myDataBeans = dataBeans.subList(0, 3);
                                        } else {
                                            myDataBeans = dataBeans;
                                        }
                                        for (int i = 0; i < myDataBeans.size(); i++) {
                                            NoticeBean.PageBean.ListBean listBean = myDataBeans.get(i);
                                            String title = listBean.getContentTitle();
                                            list.add(title + "");
                                        }
                                        //自定义的图片适配器，也可以使用默认的BannerImageAdapter
                                        noticeBannerAdapter = new NoticeBannerAdapter(context, list);
                                        binding.banner.setAdapter(noticeBannerAdapter)
                                                .addBannerLifecycleObserver(getActivity())//添加生命周期观察者
                                                .setOnBannerListener(new OnBannerListener() {
                                                    @Override
                                                    public void OnBannerClick(Object data, int position) {
                                                        Bundle bundle = new Bundle();
                                                        bundle.putInt("type", 0);
                                                        IntentUtils.getInstance().readyGo(getActivity(), NotificationActivity.class, bundle);
                                                    }
                                                })
                                                .setIndicator(new CircleIndicator(context.getApplicationContext()), false);//设置指示器
                                    }
                                }


                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }
                });

    }
}
